<template>
  <view class="change-mobile-page">
    <header class="header">
      <image class="header-image" src="/static/header-bg.png" mode="aspectFill"></image>
      
      <view class="hero-content">
        <!-- 左侧文本区域 -->
        <view class="hero-text">
          <text class="welcome">更改手机号</text>
          <!-- <text class="slogan">验证原手机号后绑定新手机号</text> -->
        </view>
        
        <!-- 右侧图片区域 -->
        <view class="hero-image">
          <image src="/static/welcome-image.png" mode="aspectFit"></image>
        </view>
      </view>
    </header>

    <!-- 表单卡片 -->
    <view class="card">
      <!-- 原手机号显示 -->
      <view class="field">
        <text class="label">当前手机号</text>
        <view class="phone-display">{{ currentMobile || '未绑定' }}</view>
      </view>
      <view class="divider"></view>
      
      <!-- 原手机号验证码 -->
      <view class="field row">
        <view class="col">
          <text class="label">原手机号验证码</text>
          <input class="input" v-model="oldCode" type="number" placeholder="请输入原手机号验证码" maxlength="6" />
        </view>
        <button class="code-btn" :disabled="oldCodeCountdown>0 || !currentMobile" @click="onGetOldCode">
          {{ oldCodeCountdown>0 ? `${oldCodeCountdown}s` : '获取验证码' }}
        </button>
      </view>
      <view class="divider"></view>
      
      <!-- 新手机号 -->
      <view class="field">
        <text class="label">新手机号</text>
        <input class="input" v-model="newMobile" type="number" placeholder="请输入新手机号" maxlength="11" />
      </view>
      <view class="divider"></view>
      
      <!-- 新手机号验证码 -->
      <view class="field row">
        <view class="col">
          <text class="label">新手机号验证码</text>
          <input class="input" v-model="newCode" type="number" placeholder="请输入新手机号验证码" maxlength="6" />
        </view>
        <button class="code-btn" :disabled="newCodeCountdown>0" @click="onGetNewCode">
          {{ newCodeCountdown>0 ? `${newCodeCountdown}s` : '获取验证码' }}
        </button>
      </view>
      <view class="divider"></view>
    </view>

    <!-- 提交按钮 -->
    <button class="submit-btn" @click="onSubmit">
      确认更改
    </button>
  </view>
</template>

<script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import sheep from '@/sheep';
  import AuthUtil from '@/sheep/api/member/auth';
  import UserApi from '@/sheep/api/member/user';

  const currentMobile = ref('');
  const oldCode = ref('');
  const newMobile = ref('');
  const newCode = ref('');
  const oldCodeCountdown = ref(0);
  const newCodeCountdown = ref(0);
  let oldTimer = null;
  let newTimer = null;

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const userInfo = await sheep.$store('user').getInfo();
      currentMobile.value = userInfo.mobile || '';
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  };

  // 获取原手机号验证码
  const onGetOldCode = () => {
    if (oldCodeCountdown.value > 0) return;
    if (!currentMobile.value) {
      return uni.showToast({ title: '当前手机号不存在', icon: 'none' });
    }
    if (currentMobile.value.length !== 11) {
      return uni.showToast({ title: '手机号格式不正确', icon: 'none' });
    }
    
    // scene=2 表示修改手机号场景
    AuthUtil.sendSmsCode(currentMobile.value, 2)
      .then(res => {
        if (res.code === 0) {
          uni.showToast({ title: '验证码已发送', icon: 'success' });
          // 开始倒计时
          oldCodeCountdown.value = 60;
          oldTimer = setInterval(() => {
            oldCodeCountdown.value--;
            if (oldCodeCountdown.value <= 0) {
              clearInterval(oldTimer);
              oldTimer = null;
            }
          }, 1000);
        } else {
          uni.showToast({ title: res.msg || '发送失败', icon: 'none' });
        }
      })
      .catch(error => {
        console.error('发送验证码失败:', error);
        uni.showToast({ title: '发送失败，请重试', icon: 'none' });
      });
  };

  // 获取新手机号验证码
  const onGetNewCode = () => {
    if (newCodeCountdown.value > 0) return;
    if (newMobile.value.length !== 11) {
      return uni.showToast({ title: '请输入正确手机号', icon: 'none' });
    }
    if (newMobile.value === currentMobile.value) {
      return uni.showToast({ title: '新手机号不能与原手机号相同', icon: 'none' });
    }
    
    // scene=2 表示修改手机号场景
    AuthUtil.sendSmsCode(newMobile.value, 2)
      .then(res => {
        if (res.code === 0) {
          uni.showToast({ title: '验证码已发送', icon: 'success' });
          // 开始倒计时
          newCodeCountdown.value = 60;
          newTimer = setInterval(() => {
            newCodeCountdown.value--;
            if (newCodeCountdown.value <= 0) {
              clearInterval(newTimer);
              newTimer = null;
            }
          }, 1000);
        } else {
          uni.showToast({ title: res.msg || '发送失败', icon: 'none' });
        }
      })
      .catch(error => {
        console.error('发送验证码失败:', error);
        uni.showToast({ title: '发送失败，请重试', icon: 'none' });
      });
  };

  // 提交更改
  const onSubmit = () => {
    // 表单验证
    if (!currentMobile.value) {
      return uni.showToast({ title: '当前手机号不存在', icon: 'none' });
    }
    if (!oldCode.value) {
      return uni.showToast({ title: '请输入原手机号验证码', icon: 'none' });
    }
    if (newMobile.value.length !== 11) {
      return uni.showToast({ title: '请输入正确的新手机号', icon: 'none' });
    }
    if (newMobile.value === currentMobile.value) {
      return uni.showToast({ title: '新手机号不能与原手机号相同', icon: 'none' });
    }
    if (!newCode.value) {
      return uni.showToast({ title: '请输入新手机号验证码', icon: 'none' });
    }

    // 准备提交数据
    const updateData = {
      mobile: newMobile.value,
      oldCode: oldCode.value,
      code: newCode.value
    };

    // 调用更新手机号接口
    UserApi.updateUserMobile(updateData)
      .then(res => {
        if (res.code === 0) {
          uni.showToast({ title: '手机号修改成功', icon: 'success' });
          // 刷新用户信息
          sheep.$store('user').getInfo();
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({ title: res.msg || '修改失败', icon: 'none' });
        }
      })
      .catch(error => {
        console.error('修改手机号失败:', error);
        uni.showToast({ title: '修改失败，请重试', icon: 'none' });
      });
  };

  onMounted(() => {
    getUserInfo();
  });

  // 页面卸载时清理定时器
  onUnmounted(() => {
    if (oldTimer) {
      clearInterval(oldTimer);
      oldTimer = null;
    }
    if (newTimer) {
      clearInterval(newTimer);
      newTimer = null;
    }
  });
</script>

<style scoped>
  .change-mobile-page {
    min-height: 100vh;
    background: #F6F6F6;
    padding: 0 0 40rpx 0;
  }
  .header {
    position: relative;
    height: 480rpx;
    width: 100%;
    margin-bottom: 0;
  }
  .header-image {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
  }
  .hero-content {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding: 0rpx 50rpx;
    z-index: 20;
  }
  
  /* 左侧文本样式 */
  .hero-text {
    flex: 1;
    padding-right: 30rpx;
  }
  .welcome { 
    display: block; 
    font-size: 48rpx; 
    font-weight: 800; 
    color: #000000; 
    margin-bottom: 12rpx; 
    margin-top: -250rpx;
  }
  .slogan { 
    display: block; 
    font-size: 26rpx; 
    color: #666; 
  }
  .hero-image {
    width: 321rpx;
    height: 306rpx;
    margin-top: -300rpx;
    margin-right: 53rpx;
  }
  .hero-image image {
    width: 100%;
    height: 100%;
    border-radius: 24rpx;
  }
  .card { 
    background: #fff; 
    border-radius: 20rpx; 
    padding: 24rpx; 
    margin-top: -40rpx; 
    margin-left: 17rpx; 
    margin-right: 17rpx;
    z-index: 30;
    position: relative;
  }
  .field {
    margin-top: 20rpx;
    margin-bottom: 8rpx; 
  }
  .row { 
    display: flex; 
    align-items: center; 
    gap: 16rpx; 
  }
  .col { 
    flex: 1; 
  }
  .label { 
    display: block; 
    font-size: 30rpx; 
    font-weight: 700; 
    color: #1f2937; 
    padding: 10rpx 20rpx;
  }
  .input { 
    width: 100%; 
    height: 80rpx; 
    border: 0; 
    background: transparent; 
    font-size: 28rpx; 
    color: #111; 
    padding: 0rpx 20rpx;
  }
  .input::placeholder {
    color: #c0c4cc; 
  }
  .phone-display {
    font-size: 28rpx;
    color: #666;
    padding: 0rpx 20rpx;
    line-height: 80rpx;
  }
  .divider { 
    height: 2rpx; 
    background: #f1f2f6; 
    margin: 8rpx 20rpx 20rpx 20rpx; 
  }
  .code-btn { 
    padding: 0 20rpx; 
    height: 72rpx; 
    line-height: 72rpx; 
    border-radius: 36rpx; 
    color: #fff; 
    font-size: 26rpx; 
    background: linear-gradient(90deg,#a78bfa,#60a5fa); 
    margin-right: 15rpx;
    border: none;
  }
  .code-btn[disabled] { 
    opacity: .5; 
  }

  .submit-btn { 
    width: 85%; 
    height: 96rpx; 
    line-height: 96rpx; 
    border-radius: 56rpx; 
    color: #fff; 
    font-size: 30rpx; 
    background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%); 
    border: none;
    outline: none;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 40rpx auto 0 auto;
    box-shadow: 0 10rpx 24rpx rgba(116, 167, 255, 0.35);
  }
</style>
